//1.导入VueRouter
import Vue from "vue";
import VueRouter from "vue-router";
//2.使用路由
Vue.use(VueRouter);
//3.创建VueRouter的实例
const router = new VueRouter({
  //tips:不想要 #（锚点）就添加下面代码
  mode: "hash",
  //4.配置路由的path和组件
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login.vue"),
    },
    {
      path: "/personal",
      name: "Personal",
      component: () => import("@/views/Personal.vue"),
    },
    {
      path: "/",
      component: () => import("@/views/Home.vue"),
    },
    {
      path: "/home",
      name: "Home",
      component: () => import("@/views/Home.vue"),
    },
    {
      path: "/viewquestion",
      name: "viewquestion",
      component: () => import("@/components/viewQues.vue"),
    },
    {
      path: "/createArticle",
      name: "createArticle",
      component: () => import("@/components/createArticle.vue"),
    },
    {
      path: "/answer",
      name: "answer",
      component: () => import("@/views/answer.vue"),
    },
    // 重定向,在项目跑起来时，访问/，定向到/home
    {
      path: "*",
      redirect: "/home",
    },
  ],
});

//路由守卫
let time = 800000;
router.beforeEach((to, from, next) => {
  // 获取本地的储存 要把数据转化成js

  let toke = null;
  let getToken = localStorage.getItem("token");
  if (getToken) toke = JSON.parse(getToken);

  if (toke) {
    //获取当前时间
    let newtime = new Date().getTime();
    if (newtime - toke.time > time) {
      localStorage.removeItem("token");
      //token失效 且当前页不是登录页 跳回登录页
      if (to.name !== "login") {
        next("/login");
      }
    } else {
      next();
    }
  } else if (to.name !== "login") {
    //没有token 且当前页不是登录页 还是停留在登录页面
    next("/login");
  }
  next();
});

//5.导入路由实例
export default router;
